package com.parachutes.aspmonitorcore.email;

import com.parachutes.aspmonitorapi.service.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发送邮件
 *
 * @author machi
 * @date 2025/01/22
 */
@Service("QQ")
public class QQEmailService implements EmailService {
    //发件人的邮箱
    @Value("${email.qq.account}")
    public static String ACCOUNT = "2417600913@qq.com";
    @Value("${email.qq.password}")
    public static String PASSWORD = "guulgzdbfyvaecig";
    //QQ邮箱这里一般是相同的，可以不修改
    @Value("${email.qq.smtp.host}")
    public static String QQ_SMTP_HOST = "smtp.qq.com";

    private Session session;
    @PostConstruct
    public void init() {
        //1.创建参数配置，用于连接邮件服务器的参数配置
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.host", QQ_SMTP_HOST);
        prop.setProperty("mail.smtp.auth", "true");
        final String smtpPort = "465";
        prop.setProperty("mail.smtp.port", smtpPort);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.protocols", "TLSv1.2");
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port", smtpPort);

        //2.根据配置创建会话
        Session session = javax.mail.Session.getInstance(prop);
        //设置debug
        session.setDebug(true);
        this.session = session;
    }

    @Override
    public Session getSession() {
        return session;
    }


    public void send(MimeMessage message) throws Exception {
        message.setFrom(new InternetAddress(ACCOUNT, "API分享平台", "UTF-8"));
        //4.根据Session获取邮件
        Transport transport = session.getTransport();

        //5.使用邮箱账号密码连接邮件服务器
        transport.connect(ACCOUNT, PASSWORD);

        //6.发送邮件，发到所有的收件地址
        transport.sendMessage(message, message.getAllRecipients());

        //7.关闭连接
        transport.close();

    }
}

